package com.molange.publish.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.molange.model.common.ResponseResult;
import com.molange.model.publish.pojos.Publish;
import com.molange.model.publish.pojos.PublishInformation;
import com.molange.publish.mapper.PublishInformationMapper;
import com.molange.publish.mapper.PublishMapper;
import com.molange.publish.service.FileStorageService;
import com.molange.publish.service.PublishInformationService;
import com.molange.publish.service.PublishService;
import com.molange.publish.utils.AppJwtUtil;
import com.molange.utils.common.BufferedImageToInputStream;
import com.molange.utils.common.VideoUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author wangshiqi
 * @version 1.0
 * @date 2023/1/28 9:56
 */
@Service
@Slf4j
public class PublishServiceImpl  extends ServiceImpl<PublishMapper, Publish> implements PublishService {


    @Autowired
    private PublishMapper publishMapper;
    @Autowired
    private PublishService publishService;
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private PublishInformationService publishInformationService;
    @Autowired
    private PublishInformationMapper publishInformationMapper;


    @Override
    @Transactional
    public ResponseResult saveFile(String token, MultipartFile file, String title) {
        //有token,判断token是否有效
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        try {
            //是否是过期
            int result = AppJwtUtil.verifyToken(claimsBody);
            if (result == 1 || result == 2) {
            }
        } catch (Exception e) {
            return ResponseResult.errorResult(100, "无效的登录状态");
        }
        //在这里获取用户登录的token,并获取token的数据
        Integer userId = (Integer) claimsBody.get("id");
        System.out.println("这里是在网关中获取的token中的用户名" + userId);
        if (file.isEmpty() || file.getSize() == 0) {
            return ResponseResult.errorResult(100,"文件为空！");
        }
        //引入自定义线程池
        //ScheduledExecutorService executor = SpringUtils.getBean("scheduledExecutorService");
        log.info("开始上传文件");
        try {

            String fileName = file.getOriginalFilename();
            System.out.println(fileName);
           /* String newName = "image/" + UUID.randomUUID().toString().replaceAll("-", "")
                    + fileName.substring(fileName.lastIndexOf("."));*/
            String s = UUID.randomUUID().toString().replaceAll("-", "");
            String newName = "video/"+userId+"/"+s+"/"+fileName;
            InputStream inputStream = file.getInputStream();
           //开始截取图片
            InputStream inputStreamPicture = file.getInputStream();
            BufferedImage bufferedImage = VideoUtil.grabberVideoFramer(inputStreamPicture);
            InputStream inputStreamNewPicture = BufferedImageToInputStream.bufferedImageToInputStream(bufferedImage);
            String newPictureName = "picture/"+userId+"/"+s+".jpeg";
            //minioUtil.putObject("minimal-tiktok-publish", newName, inputStream);
            //String videoUrl = minioUtil.getObjectUrl("minimal-tiktok-publish", newName);
            //minioUtil.putObject("minimal-tiktok-publish",newPictureName,inputStreamNewPicture);
            //String pictureUrl = minioUtil.getObjectUrl("minimal-tiktok-publish",newPictureName);
            log.info("开始上传视频");
            String pictureUrl = fileStorageService.uploadImgFile("", newPictureName, inputStreamNewPicture);
            String videoUrl = fileStorageService.uploadVideoFile("", newName, inputStream);
            inputStream.close();
            log.info("视频上传完成");
            //上传成功，获取内容到数据库
            Publish publish=new Publish();
            publish.setUserId(userId);
            publish.setStatus(0);
            publish.setTitle(title);
            publish.setUrl(videoUrl);
            publish.setPictureUrl(pictureUrl);
            publish.setCreatTime(new Date());
            save(publish);
            PublishInformation information=new PublishInformation();
            information.setComment(0);
            information.setLikes(0);
           information.setPublishId(publish.getId());
            publishInformationService.save(information);
            log.info("保存成功");
            return ResponseResult.okResult(0,"视频上传完成");
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.errorResult(100,"上传失败");
        }
    }

    /**
     * 获取视频流
     * @param date
     * @param num
     * @return
     */
    @Override
    public List<Publish> loadPublish(String date,int num) {
        log.info("开始获取用户流接口，调用数据库数据");
        if (num==30){
            //说明本次请求限制为30
            List<Publish> publishListLimit = publishMapper.getPublishListLimit(new Date());
            return publishListLimit;
        }
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date parse=new Date();
        try {
            parse = simpleDateFormat.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        log.info("开始调用数据");
        return  publishMapper.loadMorePublish(parse);
    }

    @Override
    public  Publish loadPublish(Integer publishList) {
        //LambdaQueryWrapper<Publish> lambdaQueryWrapper=new LambdaQueryWrapper();
        //lambdaQueryWrapper.eq(Publish::getId,publishList);
        //获取信息
        //Publish publishListByPublsihId = publishService.getOne(lambdaQueryWrapper);
        Publish byId = publishService.getById(publishList);
        //进行填充
        return byId;
    }

    @Override
    public PublishInformation loadPublishInformation(Integer publishInformationList) {
        LambdaQueryWrapper<PublishInformation> queryWrapper=new LambdaQueryWrapper();
        queryWrapper.eq(PublishInformation::getPublishId,publishInformationList);
        PublishInformation one = publishInformationService.getOne(queryWrapper);
        return one ;
    }
}
